package org.flyframework.dnd
{
	import flash.events.MouseEvent;
	
	import mx.core.DragSource;
	import mx.core.IFlexDisplayObject;
	import mx.core.IUIComponent;
	import mx.events.DragEvent;
	import mx.managers.DragManager;
	
	import org.flyframework.Fly;
	
	/**
	 * Draggable...
	 * 
	 * @author Ben Edwards
	 */
	public class Draggable
	{
		
		protected var initiator:IUIComponent;
		
		protected var dragSource:DragSource = new DragSource();
		protected var dragVisual:IFlexDisplayObject;
		
		
		//--------------------------------------------------------------------------
		// Init
		//--------------------------------------------------------------------------
		
		public function Draggable( component:IUIComponent )
		{
			this.initiator = component;
			
			// a mouseDown event will start the drag
			this.initiator.addEventListener( MouseEvent.MOUSE_DOWN, _doDrag );
		}
		

		//--------------------------------------------------------------------------
		// Callables
		//--------------------------------------------------------------------------
		
		public function sourceData( format:String, data:Object ):Draggable
		{
			this.dragSource.addData( data, format );
			
			return this;
		}
		
		public function sourceHandler( format:String, handler:Function ):Draggable
		{
			this.dragSource.addHandler( handler, format );
			
			return this;
		}
		
		public function useVisual( visual:IFlexDisplayObject ):Draggable
		{
			this.dragVisual = visual;
			
			return this;
		}
		
		
		public function dragStart( startFunction:Function, flags:uint=0 ):Draggable
		{
			// a dragStart event occurs when...
			//this.initiator.addEventListener( DragEvent.DRAG_START, startFunction );
			Fly.addListener( this.initiator, DragEvent.DRAG_START, startFunction, flags );
			
			return this;
		}
		
		public function dragComplete( completeFunction:Function, flags:uint=0 ):Draggable
		{
			// a dragComplete event occurs when...
			//this.initiator.addEventListener( DragEvent.DRAG_COMPLETE, completeFunction );
			Fly.addListener( this.initiator, DragEvent.DRAG_COMPLETE, completeFunction, flags );
			
			return this;
		}
		
		
		//--------------------------------------------------------------------------
		// Event Handlers
		//--------------------------------------------------------------------------
		
		protected function _doDrag( mouseEvent:MouseEvent ):void
		{
			DragManager.doDrag( this.initiator, this.dragSource, mouseEvent, this.dragVisual );
//			DragManager.doDrag( mouseEvent.currentTarget as IUIComponent, this.dragSource, mouseEvent, this.dragVisual );
		}
		
		
	}
}